﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GameplayControl : MonoBehaviour
{
	public bool canFlipCard = true;
	public static GameplayControl instance;
	// Use this for initialization
	public Card choosingCard;
	public List<Card> listCardActive, listCardInactive;
	public Character bunny, wolf, cat;
	public Text tHp, tMonsterHp, tMonsterTurnCount;
	public Image iMonsterTurnBg;
	int _hp;
	public HpLoseEffect hpLoseEffect;
	public List<Card> listIceCard;
	public bool isLastTurnMatch = false;
	public GameObject boardBackground;
	public Text tLevel;

	// UI
	public GameObject winPopup, losePopup, pausePopup;

	// Hp cua nguoi choi
	public int hp {
		get { return _hp; }
		set {
			if (value < 0) {
				value = 0;
				// death 
				GameManager.gameState = GameState.LOSE;
				losePopup.SetActive (true);
			}
			_hp = value;
			tHp.text = value.ToString ();

		}
	}

	int _monsterHp;
	// hp cua monster
	public int monsterHp {
		get { return _monsterHp; }
		set {
			if (value <= 0) {
				_monsterHp = 0;
				monster.characterControl.Death ();
			} else {
				_monsterHp = value;
			}
			tMonsterHp.text = _monsterHp.ToString ();
		}
	}

	int _turnCount;
	// bo dem turn
	public int turnCount {
		get { return _turnCount; }
		set {
			if (GameManager.gameState != GameState.PLAYING) {
				_turnCount = value;
				tMonsterTurnCount.text = _turnCount.ToString ();
				return;
			}
			foreach (Card _iceCard in listIceCard.ToArray()) {
				_iceCard.iceCardLevel--;
				if (_iceCard.iceCardLevel <= 0) {
					listIceCard.Remove (_iceCard);
				}
			}
			Debug.Log ("Next turn aaaa " + value);
			if (playerShieldLevel > 0) {
				playerShieldLevel--;
			}
			if (value > 0) {
				_turnCount = value;
				if (monster.powerTurn == true && value < monster.turn && isLastTurnMatch == false && GameManager.gameState == GameState.PLAYING) {
					Debug.Log ("MonsterPowerTurn : " + monster.powerTurn);
					monster.characterControl.Attack (monster.atk, false);
				}
			} else if (value <= 0) {
				_turnCount = 0;
				// monster tan cong nguoi choi
				if (monster.powerTurn == false) {
					monster.characterControl.Attack (monster.atk, false);
				} else if (monster.turn == 0 && isLastTurnMatch == false && GameManager.gameState == GameState.PLAYING) {
					monster.characterControl.Attack (monster.atk, false);
				} else {
					//special skill
					switch (monster.id) {
					case 9:
					case 10:
						Invoke ("SkillChangePos", 0.5F);
						break;
					case 100:
						Invoke ("SkillIce", 0.5F);
						break;
					case 200:
						Invoke ("SkillRemoveCard", 0.5F);
						break;
					}
				}
				if (monster.turn > 0) {
					Invoke ("RefillTurn", 1F);
				}
			}
			tMonsterTurnCount.text = _turnCount.ToString ();


		}
	}

	void SkillRemoveCard ()
	{
		AudioManager.instance.PlaySound (AudioClipType.atk_burn);
		int p1 = Random.Range (0, listCardActive.Count - 1);
		for (int i = 0; i < listCardActive.Count; i++) {
			if (i != p1 && listCardActive [i].type == listCardActive [p1].type) {
				Card c1 = listCardActive [p1];
				Card c2 = listCardActive [i];

				listCardInactive.Add (c1);
				listCardInactive.Add (c2);
				listCardActive.Remove (c1);
				listCardActive.Remove (c2);
				c1.gameObject.SetActive (false);
				c2.gameObject.SetActive (false);
				return;
			}

		}
		// kiem tra neu het card thi cho thua 
		if (listCardActive.Count <= 0) {
			GameplayControl.instance.hp = 0;
		}
	}

	void SkillChangePos ()
	{
		AudioManager.instance.PlaySound (AudioClipType.atk_burn);
		int p1 = Random.Range (0, listCardActive.Count - 1);
		int p2 = Random.Range (0, listCardActive.Count - 1);
		while (p2 == p1) {
			p2 = Random.Range (0, listCardActive.Count - 1);
		}

		CardType _temp = listCardActive [p1].type;
		listCardActive [p1].type = listCardActive [p2].type;
		listCardActive [p2].type = _temp;
		listCardActive [p1].ChangePosEffect ();
		listCardActive [p2].ChangePosEffect ();
	}

	void SkillIce ()
	{
		AudioManager.instance.PlaySound (AudioClipType.atk_freeze);
		int p1 = Random.Range (0, listCardActive.Count - 1);
		int p2 = Random.Range (0, listCardActive.Count - 1);
		while (p2 == p1) {
			p2 = Random.Range (0, listCardActive.Count - 1);
		}

		listCardActive [p1].iceCardLevel = 4;
		listCardActive [p2].iceCardLevel = 4;
		listIceCard.Add (listCardActive [p1]);
		listIceCard.Add (listCardActive [p2]);


	}

	public GameObject shield;
	public Text tShieldLevel;
	int _playerShieldLevel = 0;

	// level cua shield , level = 0 => ko hien
	public int playerShieldLevel {
		get {
			return _playerShieldLevel;
		}
		set {
			_playerShieldLevel = value;
			if (value > 0) {
				shield.transform.position = bunny.transform.position + new Vector3 (0.9F, 0.3F, 0);
				shield.SetActive (true);
				tShieldLevel.text = value.ToString ();
			} else {
				shield.SetActive (false);
			}
		}
	}

	void RefillTurn ()
	{
		turnCount = monster.turn;
	}

	int round = 1;
	public MonsterModule monster;
	public GameObject monsterPos;

	void Awake ()
	{
		listIceCard = new List<Card> ();
		listCardActive = new List<Card> ();
		listCardInactive = new List<Card> ();
		instance = this;
	}

	// tao emeny tiep theo , neu ko co => win
	public void NextEnemy ()
	{
		GameManager.gameState = GameState.CHANGING_ENEMY;
		round++;
		if (GameManager.levelDict.ContainsKey (GameManager.currentLevel + "mon" + round)) {
			CreateEnemy ();
			GameManager.gameState = GameState.PLAYING;
			//StartNewGame ();
		} else {
			// chien thang
			//Debug.Log ("Chien thang");
			GameManager.gameState = GameState.WIN;
			winPopup.SetActive (true);
		}
	}

	public void CreateEnemy ()
	{
		if (GameManager.levelDict.ContainsKey (GameManager.currentLevel + "mon" + round)) {
			int enemyId = int.Parse (GameManager.levelDict [GameManager.currentLevel + "mon" + round].ToString ());
			//Debug.Log ("EnemyId : " + enemyId);
			monster = new MonsterModule ();
			monster.atk = int.Parse (GameManager.enemyDict ["1Atk" + enemyId].ToString ());
			monster.hp = int.Parse (GameManager.enemyDict ["1HP" + enemyId].ToString ());
			monster.id = enemyId;
			monster.spriterName = GameManager.enemyDict ["1Spriter" + enemyId].ToString ();
			monster.turn = GameManager.enemyDict.ContainsKey ("1TNum" + enemyId) ? int.Parse (GameManager.enemyDict ["1TNum" + enemyId].ToString ()) : 0;

			if (monster.turn > 0) {
				iMonsterTurnBg.gameObject.SetActive (true);
			} else {
				iMonsterTurnBg.gameObject.SetActive (false);
			}
			//monster.powerTurn = true;
			monster.powerTurn = GameManager.enemyDict ["1PowerTurn" + enemyId].ToString () == "yes" ? true : false;
			monster.type = GameManager.enemyDict ["1Type" + enemyId].ToString ();
			monsterHp = monster.hp;
			monster.audioNam = GameManager.enemyDict ["1Audio" + enemyId].ToString ();
			// 
			GameObject monsterObj = (GameObject)Instantiate (GameDefine.instance.GetMonsterPrefapByName (monster.spriterName), monsterPos.transform.position, Quaternion.Euler (0, 0, 0));
			monster.characterControl = monsterObj.GetComponent<Character> ();
			turnCount = monster.turn;
			monster.characterControl.monster = monster;
			//Debug.Log ("Init turn");
		} else {
			Debug.Log ("Khong ton tai " + GameManager.currentLevel + "mon" + round);
		}
	}

	void Start ()
	{
		AudioManager.instance.AS_MUSIC.Stop ();
		AudioManager.instance.PlayMusic (AudioClipType.battle);
		tLevel.text = "等级 " + GameManager.currentLevel;
		hp = 20 + GameManager.dataSave.hpAdd;
		CreateEnemy ();
		StartCoroutine (CreateBoard ());
	}

	// tao bang card
	IEnumerator CreateBoard ()
	{

		GameDefine.instance.listCardTypeCreate.Shuffle ();
		yield return null;
		for (int x = 0; x < 5; x++) {
			for (int y = 0; y < 5; y++) {
				GameObject card = (GameObject)Instantiate (GameDefine.instance.cardPrefap, new Vector3 (boardBackground.transform.position.x - 2F + x, boardBackground.transform.position.y + 2F - y, 0), Quaternion.Euler (0, 0, 0));
				Card _card = card.GetComponent<Card> ();
				listCardActive.Add (_card);
				card.transform.SetParent (boardBackground.transform);
				_card.type = GameDefine.instance.listCardTypeCreate [x * 5 + y];
			}
		}
		yield return new WaitForSecondsRealtime (3F); 
		GameManager.gameState = GameState.PLAYING;

	}

	void StartNewGame ()
	{
		GameDefine.instance.listCardTypeCreate.Shuffle ();
		for (int i = 0; i < listCardInactive.Count; i++) {
			Card _card = listCardInactive [i];
			listCardActive.Add (_card);
			_card.type = GameDefine.instance.listCardTypeCreate [i];
			_card.gameObject.SetActive (true);
			_card.faceType = CardFaceType.FACE_DOWN;
		}
		listCardInactive.Clear ();
	}

	public void MenuClick ()
	{
		Time.timeScale = 1;
		LoadSceneFading.LoadScene ("scn_select_level");
	}

	public void ReplayClick ()
	{
		Time.timeScale = 1;
		LoadSceneFading.LoadScene ("scn_play");
	}

	public void NextClick ()
	{
		if (GameManager.currentLevel < GameManager.dataSave.levelMax) {
			GameManager.currentLevel++;
			Time.timeScale = 1;
			LoadSceneFading.LoadScene ("scn_play");
		}
	}

	public void Pause ()
	{
		pausePopup.SetActive (true);
		//AdsControl.Instance.showAds ();
	}
}
